package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.cache.redis.RedisHelper;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.vo.dict.DictQueryVO;
import com.bifang.module.base.common.vo.dict.SelectVO;
import com.bifang.module.base.common.vo.excel.ExcelModelVO;
import com.bifang.module.base.common.vo.excel.ExcelParamVO;
import com.bifang.module.base.common.vo.excel.ExcelVO;
import com.bifang.module.base.core.helper.DictHelper;
import com.bifang.module.base.core.helper.ExcelCommonHelper;
import com.bifang.module.base.core.integration.DictIntegration;
import com.bifang.module.base.core.integration.ExcelIntegration;
import com.bifang.module.system.core.dao.model.SysApplication;
import com.bifang.module.system.core.dao.service.SysApplicationService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.constant.EduCache;
import com.jwsoft.manager.common.enums.CardTypeEnum;
import com.jwsoft.manager.common.enums.JhSyncImportEnum;
import com.jwsoft.manager.common.enums.JhSyncTypeEnum;
import com.jwsoft.manager.common.vo.eduSyncJhApprove.EduSyncJhApproveKeyVO;
import com.jwsoft.manager.common.vo.eduSyncJhApprove.EduSyncJhApproveQueryVO;
import com.jwsoft.manager.common.vo.eduSyncJhApprove.EduSyncJhApproveVO;
import com.jwsoft.manager.common.vo.eduSyncJhDelete.EduSyncJhDeleteQueryVO;
import com.jwsoft.manager.core.dao.model.EduSyncJhApply;
import com.jwsoft.manager.core.dao.model.EduSyncJhApprove;
import com.jwsoft.manager.core.dao.model.EduSyncJhApproveError;
import com.jwsoft.manager.core.dao.model.EduSyncJhEnroll;
import com.jwsoft.manager.core.dao.service.*;
import com.jwsoft.manager.core.integration.EduSyncJhApproveIntegration;
import com.jwsoft.manager.core.integration.EduSyncJhImportBatchIntegration;
import com.jwsoft.manager.core.util.EduDesensitizeUtil;
import com.jwsoft.manager.core.util.EduHelper;
import com.jwsoft.manager.core.util.ExcelUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 金华市审核专库同步情况表业务实现类
 *
 * @author zhiyuan
 * @since 2024-04-08
 */
@ApiService(funcCode = "syncJhApprove", title = "金华市审核专库同步情况表")
public class EduSyncJhApproveIntegrationImpl implements EduSyncJhApproveIntegration {

    @Autowired
    public EduSyncJhApproveService eduSyncJhApproveService;
    @Autowired
    private EduSyncJhImportBatchIntegration importBatchIntegration;
    @Autowired
    private ExcelIntegration excelIntegration;
    @Autowired
    ExcelUtils excelUtils;
    @Autowired
    private ExcelCommonHelper excelCommonHelper;
    @Autowired
    private EduSyncJhImportBatchService importBatchService;
    @Autowired
    DictHelper dictHelper;
    @Autowired
    private EduHelper eduHelper;
    @Autowired
    private DictIntegration dictIntegration;
    @Autowired
    private EduSyncJhApproveErrorService approveErrorService;
    @Autowired
    private EduSyncJhEnrollService enrollService;
    @Autowired
    private EduSyncJhApplyService eduSyncJhApplyService;
    @Value("${spring.servlet.multipart.location}")
    private String tempPath;
    @Autowired
    private RedisHelper redisHelper;

    @Autowired
    private SysApplicationService applicationService;
    @Override
    @OpApi(funcCode = "syncJhApprove0001", title = "金华市审核专库同步情况表分页查询", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE)
    public PageInfo<EduSyncJhApproveVO> getList(EduSyncJhApproveQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        //取出脱敏字段，判断是否为空
        Boolean desensitizeFlag = vo.getDesensitizeFlag();
        if (desensitizeFlag == null){
            desensitizeFlag = true;
        }
        String loginAreaCode = SessionUtil.getAreaCode();
        if (StringUtils.isBlank(loginAreaCode)) {
            throw new AppException("登录的账号未配置行政区划，请联系管理员进行处理！");
        }
        QueryWrapper<EduSyncJhApprove> queryWrapper = new QueryWrapper<>();
        String areaCode = eduHelper.thisAreaCode();
        if (!loginAreaCode.equals(areaCode)) {
            //比对行政区划
            queryWrapper.lambda().eq(EduSyncJhApprove::getApplyCountyCode, loginAreaCode);
        }
        queryWrapper.lambda()
                .eq(!ObjectUtils.isEmpty(vo.getYear()),EduSyncJhApprove::getYear, vo.getYear())
                .eq(StringUtils.isNotBlank(vo.getIdcard()), EduSyncJhApprove::getIdcard, vo.getIdcard())
                .like(StringUtils.isNotBlank(vo.getName()), EduSyncJhApprove::getName, vo.getName())
                .eq(StringUtils.isNotBlank(vo.getCardType()), EduSyncJhApprove::getCardType, vo.getCardType())
                .eq(StringUtils.isNotBlank(vo.getApproveState()), EduSyncJhApprove::getApproveState, vo.getApproveState())
                .eq(StringUtils.isNotBlank(vo.getSchoolCategory()), EduSyncJhApprove::getSchoolCategory, vo.getSchoolCategory())
                .eq(StringUtils.isNotBlank(vo.getApplyCountyCode()), EduSyncJhApprove::getApplyCountyCode, vo.getApplyCountyCode())
                .orderByDesc(EduSyncJhApprove::getUpdateTime, EduSyncJhApprove::getCreateTime, EduSyncJhApprove::getName);
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        List<EduSyncJhApprove> list = eduSyncJhApproveService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduSyncJhApprove> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduSyncJhApproveVO> resultList = Convert.toList(EduSyncJhApproveVO.class, pageInfo.getList());
        // 转义数据字典值
        dictHelper.valueToName(resultList, Arrays.asList(JhSyncTypeEnum.values()));
        if (desensitizeFlag) {
            for (EduSyncJhApproveVO eduSyncJhApproveVO : resultList) {
                eduSyncJhApproveVO.setName(EduDesensitizeUtil.desensitizeFullName(eduSyncJhApproveVO.getName()));
                eduSyncJhApproveVO.setIdcard(EduDesensitizeUtil.desensitizeIdcard(eduSyncJhApproveVO.getIdcard()));
            }
        }
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "syncJhApprove0002", title = "金华市审核专库同步情况表根据主键查询详情", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE)
    public EduSyncJhApproveVO getById(EduSyncJhApproveKeyVO vo) {
        EduSyncJhApprove entity = eduSyncJhApproveService.getById(vo.getJhApproveId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduSyncJhApproveVO result = Convert.convert(EduSyncJhApproveVO.class, entity);
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "syncJhApprove0003", title = "金华市审核专库同步情况表保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduSyncJhApproveVO vo) {
        //主键为空为新增校验

        //主键不为空为修改校验
        if (vo.getYear() == null) {
            vo.setYear(eduHelper.thisYear());
        }
        if (StringUtils.isBlank(vo.getSchoolCategory())) {
            throw new AppException("学段不能为空！");
        }
        if (StringUtils.isBlank(vo.getApproveState())) {
            throw new AppException("审核状态不能为空！");
        }
        if (ObjectUtils.isEmpty(vo.getApproveTime())) {
            throw new AppException("审核时间不能为空！");
        }
        if (StringUtils.isBlank(vo.getApproveHuman())) {
            throw new AppException("审核人不能为空！");
        }
        if (StringUtils.isBlank(vo.getCardType())) {
            throw new AppException("证件类型不能为空！");
        }
        if (StringUtils.isBlank(vo.getName())) {
            throw new AppException("姓名不能为空！");
        }
        if (StringUtils.isBlank(vo.getIdcard())) {
            throw new AppException("证件号码不能为空！");
        }
        if (StringUtils.isBlank(vo.getApplyCountyCode())) {
            throw new AppException("报名所在区县码不能为空！");
        }
        if (vo.getCardType().equalsIgnoreCase(CardTypeEnum.idcard.getType())) {
            if (!IdcardUtil.isValidCard(vo.getIdcard())) {
                throw new AppException("身份证格式有误！");
            }
        }

        //校验审核状态是否符合要求
        if (!vo.getApproveState().equalsIgnoreCase("1")
                && !vo.getApproveState().equalsIgnoreCase("2")) {
            throw new AppException("审核状态只能为数字1或2，1代表通过，2代表不通过");
        }
        //校验学段格式是否符合要求
        if (  !vo.getSchoolCategory().equalsIgnoreCase("2")
                && !vo.getSchoolCategory().equalsIgnoreCase("3")) {
            throw new AppException("学段只能为数字2或3，2代表小学，3代表初中");
        }
        //校验证件类型是否符合要求
        if (!vo.getCardType().equalsIgnoreCase("01")
                && !vo.getCardType().equalsIgnoreCase("02")
                && !vo.getCardType().equalsIgnoreCase("03")
                && !vo.getCardType().equalsIgnoreCase("04")
                && !vo.getCardType().equalsIgnoreCase("05")
                && !vo.getCardType().equalsIgnoreCase("06")
                && !vo.getCardType().equalsIgnoreCase("99")) {
            throw new AppException("证件类型只能为数字01或02或03或04或05或06或99，01代表身份证，02代表护照，03代表台胞证，04代表台湾居民来往大陆通行证，05代表港澳居民往来内地通行证，06代表外国人永久居留身份证，99代表其他证件");
        }
        //校验区县码是否为数字
        if (!StringUtils.isNumeric(vo.getApplyCountyCode())) {
            throw new AppException("报名所在区县码只能为数字");
        }
    }

    @Override
    @OpApi(funcCode = "syncJhApprove0004", title = "金华市审核专库同步情况表新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "syncJhApprove0004",
            operationName = "金华市审核专库同步情况表新增",
            dataType = "jhApproveId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduSyncJhApproveVO add(EduSyncJhApproveVO vo) {
        //保存前校验
        checkSave(vo);
        EduSyncJhApply syncJhApply = checkApplyData(vo);
        if (syncJhApply == null){
            throw new AppException("同步报名数据不存在，请先添加同步报名数据!");
        }
        vo.setJhApplyId(syncJhApply.getJhApplyId());
        QueryWrapper<EduSyncJhApprove> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduSyncJhApprove::getYear, vo.getYear())
                .eq(EduSyncJhApprove::getApplyCountyCode, vo.getApplyCountyCode())
                .eq(EduSyncJhApprove::getIdcard, vo.getIdcard());
        if (eduSyncJhApproveService.count(queryWrapper) > 0) {
            throw new AppException("该学生报名区域已存在本年度审核数据!  ");
        }
        //保存数据
        EduSyncJhApprove entity = Convert.convert(EduSyncJhApprove.class, vo);
        eduSyncJhApproveService.save(entity);
        if (entity.getJhApplyId() == null){
            throw new AppException("报名同步数据id 不存在，无法进行数据添加，数据有误");
        }
        //将主键设置回vo使操作日志可以取到
        vo.setJhApproveId(entity.getJhApproveId());
        return vo;
    }

    /**
     * 根据年度和身份证信息返回报名同步数据
     * @param vo
     * @return
     */
    private EduSyncJhApply checkApplyData(EduSyncJhApproveVO vo) {
        if (vo.getYear() == null){
            throw new AppException("年份不能为空!");
        }
        QueryWrapper<EduSyncJhApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduSyncJhApply::getYear, vo.getYear())
                .eq(EduSyncJhApply::getApplyCountyCode, vo.getApplyCountyCode())
                .eq(EduSyncJhApply::getIdcard, vo.getIdcard());
        EduSyncJhApply syncJhApply = eduSyncJhApplyService.getOne(queryWrapper, false);
        return syncJhApply;
    }

    @Override
    @OpApi(funcCode = "syncJhApprove0005", title = "金华市审核专库同步情况表修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "syncJhApprove0005",
            operationName = "金华市审核专库同步情况表修改",
            dataType = "jhApproveId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduSyncJhApproveVO edit(EduSyncJhApproveVO vo) {
        if (ObjectUtils.isEmpty(vo.getJhApproveId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduSyncJhApprove oldEntity = eduSyncJhApproveService.getById(vo.getJhApproveId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //校验年份和身份证是否存在
        QueryWrapper<EduSyncJhApprove> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduSyncJhApprove::getYear, vo.getYear())
                .eq(EduSyncJhApprove::getApplyCountyCode, vo.getApplyCountyCode())
                .eq(EduSyncJhApprove::getIdcard, vo.getIdcard());
        if (eduSyncJhApproveService.count(queryWrapper) >= 1) {
            throw new AppException("该学生报名区域已存在本年度审核数据!  ");
        }
        //保存数据
        EduSyncJhApprove entity = Convert.convert(EduSyncJhApprove.class, vo);
        if (entity.getJhApplyId() == null){
            throw new AppException("报名同步数据id 不存在，无法进行数据修改，数据有误");
        }
        eduSyncJhApproveService.updateById(entity);
        return vo;
    }

    @Override
    @OpApi(funcCode = "syncJhApprove0006", title = "金华市审核专库同步情况表根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "syncJhApprove0006",
            operationName = "金华市审核专库同步情况表删除",
            dataType = "jhApproveId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduSyncJhApproveKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getJhApproveId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduSyncJhApprove entity = eduSyncJhApproveService.getById(vo.getJhApproveId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        //判断录取库有没有学生数据，有的提示先删除录取库数据
        QueryWrapper<EduSyncJhEnroll> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduSyncJhEnroll::getIdcard, entity.getIdcard())
                .eq(EduSyncJhEnroll::getYear, entity.getYear());
        if (enrollService.count(queryWrapper) > 0) {
            throw new AppException("该学生在录取同步表库中有数据，无法删除报名同步库中的数据！");
        }
        eduSyncJhApproveService.removeById(vo.getJhApproveId());
    }

    @Override
    @OpApi(funcCode = "syncJhApprove0007", title = "金华市审核专库同步情况-excel导出",
            funcType = FuncTypeEnum.other, checkPrivilege = BoolEnum.FALSE)
    public void exportJhApproveInfo(EduSyncJhApproveQueryVO vo, HttpServletResponse response) {
        if (ObjectUtils.isEmpty(vo.getModelCode())) {
            throw new AppException("请传入模板编码!  ");
        }
        ExcelVO excelVO = new ExcelVO();
        excelVO.setModelCode(vo.getModelCode());
        Map<String, List<SelectVO>> dictMap = new HashMap<>();
        //设置学段
        dictMap.put("schoolCategory", importBatchIntegration.getSchoolCategory());
        //设置身份证类型下拉框信息
        dictMap.put("cardType", importBatchIntegration.getCardTypeDict());
        //获取审核状态
        dictMap.put("approveState", importBatchIntegration.getApproveStateDict());
        excelVO.setDictMap(dictMap);
        ExcelModelVO excelModelVO = excelIntegration.getModel(excelVO);
        List<ExcelParamVO> paramVOList = excelModelVO.getParamVOList();
        paramVOList = paramVOList.stream().filter(item ->{
            return !"remarks".equals(item.getKey());
        }).collect(Collectors.toList());
        excelModelVO.setParamVOList(paramVOList);
        String destFilePath = this.tempPath + "/" + IdUtil.fastSimpleUUID() + "." + excelModelVO.getExcelType();
        int pageNum = 1;
        //如果数据为空，就下载模板给他
        if(queryCountByVO(vo) == 0){
            excelCommonHelper.downloadModel(excelModelVO,null,response);
            return;
        }
        setData(excelModelVO, null, destFilePath, vo, pageNum);
        String fileName = "金华市审核同步数据" + DateUtil.today();
        if (StringUtils.isBlank(fileName)) {
            fileName =
                    excelModelVO.getModelName()
                            + "_"
                            + DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN)
                            + "."
                            + (StringUtils.isBlank(excelModelVO.getExcelType())
                            ? "xls"
                            : excelModelVO.getExcelType());
        }
        File file = FileUtil.file(destFilePath);
        BufferedInputStream in = null;
        try {
            in = FileUtil.getInputStream(file);
            ServletUtil.write(response, in, "application/octet-stream;charset=utf-8", fileName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileUtil.del(destFilePath);
        }
    }

    private int queryCountByVO(EduSyncJhApproveQueryVO vo) {
        String loginAreaCode = SessionUtil.getAreaCode();
        if (StringUtils.isBlank(loginAreaCode)) {
            throw new AppException("登录的账号未配置行政区划，请联系管理员进行处理！");
        }
        QueryWrapper<EduSyncJhApprove> queryWrapper = new QueryWrapper<>();
        String areaCode = eduHelper.thisAreaCode();
        if (!loginAreaCode.equals(areaCode)) {
            //比对行政区划
            queryWrapper.lambda().eq(EduSyncJhApprove::getApplyCountyCode, loginAreaCode);
        }
        queryWrapper.lambda()
                .eq(!ObjectUtils.isEmpty(vo.getYear()),EduSyncJhApprove::getYear, vo.getYear())
                .eq(StringUtils.isNotBlank(vo.getIdcard()), EduSyncJhApprove::getIdcard, vo.getIdcard())
                .like(StringUtils.isNotBlank(vo.getName()), EduSyncJhApprove::getName, vo.getName())
                .eq(StringUtils.isNotBlank(vo.getCardType()), EduSyncJhApprove::getCardType, vo.getCardType())
                .eq(StringUtils.isNotBlank(vo.getApproveState()), EduSyncJhApprove::getApproveState, vo.getApproveState())
                .eq(StringUtils.isNotBlank(vo.getSchoolCategory()), EduSyncJhApprove::getSchoolCategory, vo.getSchoolCategory())
                .eq(StringUtils.isNotBlank(vo.getApplyCountyCode()), EduSyncJhApprove::getApplyCountyCode, vo.getApplyCountyCode()) ;
        return (int) eduSyncJhApproveService.count(queryWrapper);
    }

    @Override
    @OpApi(funcCode = "syncJhApprove0008", title = "金华市审核专库同步情况-excel导入并保存",
            funcType = FuncTypeEnum.other, checkPrivilege = BoolEnum.FALSE)
    public void inputAndSaveJhApproveInfo(ExcelVO excelVO, MultipartFile file) {
        ExcelModelVO excelModelVO = excelUtils.getModel(excelVO);
        InputStream in = null;
        try {
            String areaCode = SessionUtil.getAreaCode();
            if (StringUtils.isBlank(areaCode)){
                throw new AppException("该账号未配置统筹区划，请先联系管理人员进行配置！");
            }
            // 根据行政区划来加锁
            String redisKey= EduCache.EdU_SYNC_JH_APPROVE_LOCK+areaCode;
            boolean lock = false;
            lock = redisHelper.hasKey(redisKey);
            if (lock) {
                throw new AppException("审核专库同步正在同步中，请稍后再试！");
            }else{
                //获取不到，就设置锁
                redisHelper.set(redisKey, true, 7200);
            }
            try {
                in = file.getInputStream();
                //记录已经导入的证件信息
                List<String> idcardList = new ArrayList<>();
                List<Map<String, Object>> list = excelCommonHelper.readExcel(excelModelVO, in, true);
                if (CollectionUtils.isEmpty(list)) {
                    throw new AppException("导入的excel文档数据为空，请填写数据后重试!");
                }
                //插入成功得到批次id
                Long importBatchId = importBatchService.createImportBatch(JhSyncImportEnum.approve);
                for (Map<String, Object> map : list) {
                    EduSyncJhApproveVO syncJhApproveVO =
                            JSON.parseObject(JSON.toJSONString(map), EduSyncJhApproveVO.class);
                    //校验数据，如果有错误，拼接到remarks中
                    String remarks = "";
                    Boolean checkFlag = importCheck(syncJhApproveVO, remarks, idcardList);
                    if (!checkFlag) {
                        //插入到错误表中
                        EduSyncJhApproveError approveError = Convert.convert(EduSyncJhApproveError.class, syncJhApproveVO);
                        //设置操作人的行政区划
                        approveError.setAreaCode(SessionUtil.getAreaCode());
                        approveError.setImportBatchId(importBatchId);
                        approveErrorService.save(approveError);
                        continue;
                    }
                    //根据身份证校验数据是否存在
                    QueryWrapper<EduSyncJhApprove> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda()
                            .select(EduSyncJhApprove::getJhApproveId)
                            .eq(EduSyncJhApprove::getIdcard, syncJhApproveVO.getIdcard())
                            .eq(EduSyncJhApprove::getYear, syncJhApproveVO.getYear());
                    //有数据查出来覆盖，没数据插入
                    EduSyncJhApprove syncJhApprove = eduSyncJhApproveService.getOne(queryWrapper, false);
                    if (!ObjectUtils.isEmpty(syncJhApprove)) {
                        syncJhApproveVO.setJhApproveId(syncJhApprove.getJhApproveId());
                    }
                    EduSyncJhApprove approve = Convert.convert(EduSyncJhApprove.class, syncJhApproveVO);
                    approve.setImportBatchId(importBatchId);
                    //单条插入
                    eduSyncJhApproveService.saveOrUpdate(approve);
                }
            } finally {
                // 释放锁
                redisHelper.del(redisKey);
            }
        } catch (AppException appEx) {
            throw appEx;
        } catch (IOException e) {
            throw new AppException("读取文件异常:" + e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @Override
    @OpApi(funcCode = "syncJhApprove0009", title = "审核同步模板下载（PC）",
            funcType = FuncTypeEnum.other, checkPrivilege = BoolEnum.FALSE)
    public void downloadModel(ExcelVO excelVO, HttpServletResponse response) {
        //填写下拉框数据
        Map<String, List<SelectVO>> dictMap = new HashMap<>();
        //设置学段
        dictMap.put("schoolCategory", importBatchIntegration.getSchoolCategory());
        //设置身份证类型下拉框信息
        dictMap.put("cardType", importBatchIntegration.getCardTypeDict());
        //获取审核状态
        dictMap.put("approveState", importBatchIntegration.getApproveStateDict());
        excelVO.setDictMap(dictMap);
        ExcelModelVO excelModelVO=excelIntegration.getModel(excelVO);
        List<ExcelParamVO> paramVOList = excelModelVO.getParamVOList();
        //模板下载去除错误描述和区县名
        List<String> removeParams = new ArrayList<>();
        removeParams.add("remarks");
        removeParams.add("applyCountyName");
        paramVOList = paramVOList.stream().filter(item ->{
            return !removeParams.contains(item.getKey());
        }).collect(Collectors.toList());
        excelModelVO.setParamVOList(paramVOList);
        excelCommonHelper.downloadModel(excelModelVO,excelVO.getRows(),response);
    }

    @Override
    public void syncDelete(EduSyncJhDeleteQueryVO vo) {
        //判断录取库有没有学生数据，有的提示先删除录取库数据
        QueryWrapper<EduSyncJhEnroll> enrollWrapper = new QueryWrapper<>();
        enrollWrapper.lambda().eq(EduSyncJhEnroll::getIdcard, vo.getIdcard())
                .eq(EduSyncJhEnroll::getApplyCountyCode, vo.getApplyCountyCode())
                .eq(EduSyncJhEnroll::getYear, vo.getYear());
        if (enrollService.count(enrollWrapper) > 0) {
            throw new AppException("该学生在录取同步表库中有数据，无法删除报名同步库中的数据！");
        }
        QueryWrapper<EduSyncJhApprove> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(EduSyncJhApprove::getYear, vo.getYear())
                .eq(EduSyncJhApprove::getApplyCountyCode, vo.getApplyCountyCode())
                .eq(EduSyncJhApprove::getIdcard, vo.getIdcard());
        EduSyncJhApprove approve = eduSyncJhApproveService.getOne(queryWrapper, false);
        if (ObjectUtils.isEmpty(approve)) {
            return;
        }
        eduSyncJhApproveService.removeById(approve.getJhApproveId());

    }

    @Override
    @Transactional
    @OpApi(funcCode = "syncSaveJhApprove0001", title = "金华市学生审核信息同步-向外暴露接口",
            funcType = FuncTypeEnum.insert, checkPrivilege = BoolEnum.FALSE,savelog = true)
    public EduSyncJhApproveVO saveSyncApproveInfo(EduSyncJhApproveVO vo, HttpServletRequest request) {
        String appId = request.getHeader("appId");
        if (StringUtils.isBlank(appId)){
            throw new AppException("应用id不能为空！");
        }

        //保存前校验
        checkSave(vo);
        DictQueryVO areaDictQueryVO = new DictQueryVO();
        areaDictQueryVO.setDictField("AREA");
        areaDictQueryVO.setDictKey(vo.getApplyCountyCode());
        String areaName = dictIntegration.getValue(areaDictQueryVO);
        if (StringUtils.isBlank(areaName)){
            throw new AppException("传入的区县编码不正确，请根据提供的接口文档规范上传！");
        }
        vo.setApplyCountyName(areaName);

        //校验行政区划和当前配置的应用id 是否一样
        SysApplication sysApplication = applicationService.getById(appId);
        //根据，来分割remarks
        String remarks = sysApplication.getRemarks();
        if (StringUtils.isEmpty(remarks)){
            throw new AppException("应用id未配置行政区划，请联系管理员进行配置！");
        }
        List areaList = Arrays.asList(remarks.split(","));
        if (!areaList.contains(vo.getApplyCountyCode())){
            throw new AppException("传入的区县编码和申请的应用区县编码不一致，应用区县编码 ["+remarks+"]请根据提供的接口文档规范上传！");
        }

        EduSyncJhApply syncJhApply = checkApplyData(vo);
        if (syncJhApply == null){
            throw new AppException("同步报名数据不存在，请先添加同步报名数据!");
        }
        vo.setJhApplyId(syncJhApply.getJhApplyId());

        //保存数据
        EduSyncJhApprove entity = Convert.convert(EduSyncJhApprove.class, vo);
        QueryWrapper<EduSyncJhApprove> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduSyncJhApprove::getYear, vo.getYear())
                .eq(EduSyncJhApprove::getApplyCountyCode, vo.getApplyCountyCode())
                .eq(EduSyncJhApprove::getIdcard, vo.getIdcard());
        if (eduSyncJhApproveService.count(queryWrapper) > 0) {
            EduSyncJhApprove approve = eduSyncJhApproveService.getOne(queryWrapper, false);
            //设置主键
            entity.setJhApproveId(approve.getJhApproveId());
        }
        if (entity.getJhApplyId() == null){
            throw new AppException("报名同步数据id 不存在，无法进行数据添加，数据有误");
        }
        eduSyncJhApproveService.saveOrUpdate(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setJhApproveId(entity.getJhApproveId());
        return vo;
    }

    @Override
    public EduSyncJhApproveVO saveSyncApproveInfo2(EduSyncJhApproveVO vo) {
        //保存前校验
        checkSave(vo);
        DictQueryVO areaDictQueryVO = new DictQueryVO();
        areaDictQueryVO.setDictField("AREA");
        areaDictQueryVO.setDictKey(vo.getApplyCountyCode());
        String areaName = dictIntegration.getValue(areaDictQueryVO);
        if (StringUtils.isBlank(areaName)){
            throw new AppException("传入的区县编码不正确，请根据提供的接口文档规范上传！");
        }
        vo.setApplyCountyName(areaName);
        EduSyncJhApply syncJhApply = checkApplyData(vo);
        if (syncJhApply == null){
            throw new AppException("同步报名数据不存在，请先添加同步报名数据!");
        }
        vo.setJhApplyId(syncJhApply.getJhApplyId());

        //保存数据
        EduSyncJhApprove entity = Convert.convert(EduSyncJhApprove.class, vo);
        QueryWrapper<EduSyncJhApprove> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduSyncJhApprove::getYear, vo.getYear())
                .eq(EduSyncJhApprove::getApplyCountyCode, vo.getApplyCountyCode())
                .eq(EduSyncJhApprove::getIdcard, vo.getIdcard());
        EduSyncJhApprove syncJhApprove = eduSyncJhApproveService.getOne(queryWrapper, false);
        if (!ObjectUtils.isEmpty(syncJhApprove)){
            //有数据，就覆盖
            entity.setJhApproveId(syncJhApprove.getJhApproveId());
        }
        eduSyncJhApproveService.saveOrUpdate(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setJhApproveId(entity.getJhApproveId());
        return vo;
    }

    /**
     * 校验excel导入数据
     * @param syncJhApproveVO
     * @param remarks
     * @param idcardList
     * @return
     */
    private Boolean importCheck(EduSyncJhApproveVO syncJhApproveVO, String remarks, List<String> idcardList) {
        if (syncJhApproveVO.getYear() == null) {
            syncJhApproveVO.setYear(eduHelper.thisYear());
        }
        boolean flag = true;

        //校验证件类型
        if (StringUtils.isBlank(syncJhApproveVO.getCardType())) {
            remarks += "证件类型不能为空!  ";
            flag = false;
        }else {
            //证件类型不为空，去除空格
            String cardType = syncJhApproveVO.getCardType().trim();
            if (Validator.isChinese(cardType)) {
                //如果为中文 根据数据字典的value  得到key 值
                DictQueryVO dictQueryVO = new DictQueryVO();
                dictQueryVO.setDictField("CARDTYPE");
                dictQueryVO.setDictValue(cardType);
                String key = dictIntegration.getKey(dictQueryVO);
                if (StringUtils.isBlank(key)) {
                    remarks += "学生证件类型数据格式不对！ 正确格式： 如 身份证/护照/台胞证/台湾居民来往大陆通行证/港澳居民往来内地通行证/外国人永久居留身份证/其他证件!  ";
                    flag = false;
                } else {
                    syncJhApproveVO.setCardType(key);
                }
            }else{
                remarks += "学生证件类型数据格式不对！ 正确格式： 如 身份证/护照/台胞证/台湾居民来往大陆通行证/港澳居民往来内地通行证/外国人永久居留身份证/其他证件!  ";
                flag = false;
            }
            syncJhApproveVO.setIdcard(syncJhApproveVO.getIdcard().trim().toUpperCase());
            //证件类型为数字，判断是否为身份证类型
            if (CardTypeEnum.idcard.getType().equals(syncJhApproveVO.getCardType())
                    && !IdcardUtil.isValidCard(syncJhApproveVO.getIdcard())) {
                remarks += "学生证件数据格式不对！";
                flag = false;
            }
        }

        //校验学段
        if (StringUtils.isBlank(syncJhApproveVO.getSchoolCategory())) {
            remarks += "学生学段不能为空!  ";
            flag = false;
        } else {
            String schoolCategory = syncJhApproveVO.getSchoolCategory().trim();
            if (Validator.isChinese(schoolCategory)) {
                DictQueryVO dictQueryVO = new DictQueryVO();
                dictQueryVO.setDictField("SCHOOLCATEGORY");
                dictQueryVO.setDictValue(schoolCategory);
                String key = dictIntegration.getKey(dictQueryVO);
                if (StringUtils.isBlank(key)) {
                    flag = false;
                    remarks += "学生学段数据格式不对！ 正确格式：如 小学/初中! ";
                } else {
                    syncJhApproveVO.setSchoolCategory(key);
                }
            } else {
                flag = false;
                remarks += "学生学段数据格式不对！ 正确格式：如 小学/初中! ";
            }
        }

        //校验审核状态
        if (StringUtils.isBlank(syncJhApproveVO.getApproveState())) {
            remarks += "审核状态不能为空!  ";
            flag = false;
        } else {
            String approveState = syncJhApproveVO.getApproveState().trim();
            if (Validator.isChinese(approveState)) {
                DictQueryVO dictQueryVO = new DictQueryVO();
                dictQueryVO.setDictField("APPROVESTATE");
                dictQueryVO.setDictValue(approveState);
                String key = dictIntegration.getKey(dictQueryVO);
                if (StringUtils.isBlank(key)) {
                    flag = false;
                    remarks += "审核状态数据格式不对！ 正确格式：如 通过/不通过!  ";
                } else {
                    syncJhApproveVO.setApproveState(key);
                }
            }else{
                flag = false;
                remarks += "审核状态数据格式不对！ 正确格式：如 通过/不通过!  ";
            }
        }

        //校验审核所在区县名
        String areaCode = SessionUtil.getAreaCode();
        DictQueryVO dictQueryVO = new DictQueryVO();
        dictQueryVO.setDictField("AREA");
        dictQueryVO.setDictKey(areaCode);
        String areaName = dictIntegration.getValue(dictQueryVO);
        syncJhApproveVO.setApplyCountyName(areaName);
        syncJhApproveVO.setApplyCountyCode(areaCode);

        //校验身份证是否存在
        if (idcardList.contains(syncJhApproveVO.getIdcard())) {
            flag = false;
            remarks += "该身份证已存在，请检查!  ";
        } else {
            idcardList.add(syncJhApproveVO.getIdcard());
        }

        // 校验审核时间
        if(ObjectUtils.isEmpty(syncJhApproveVO.getApproveTime())){
            flag = false;
            remarks += "审核时间不存在!  ";
        }

        //校验审核人
        if (StringUtils.isBlank(syncJhApproveVO.getApproveHuman())){
            flag = false;
            remarks += "审核人不能为空!  ";
        }


        //查询报名信息是否存在
        EduSyncJhApply syncJhApply = checkApplyData(syncJhApproveVO);
        if(syncJhApply == null){
            flag = false;
            remarks += "该学生同步报名信息不存在,请先添加该学生报名信息！ ";
        }else{
            syncJhApproveVO.setJhApplyId(syncJhApply.getJhApplyId());
        }
        syncJhApproveVO.setRemarks(remarks);

        return flag;
    }

    private void setData(ExcelModelVO excelModelVO, ExcelWriter excelWriter, String destFilePath, EduSyncJhApproveQueryVO vo, int pageNum) {
        vo.setPageNum(pageNum);
        vo.setPageSize(500);
        boolean closeFlag = false;
        try {
            PageInfo<EduSyncJhApproveVO> pageInfo = getList(vo);
            String total = String.valueOf(pageInfo.getTotal());
            List<Map<String, Object>> list = new ArrayList<>();
            if (!CollectionUtils.isEmpty(pageInfo.getList())) {
                for (EduSyncJhApproveVO approveVO : pageInfo.getList()) {
                    //将数据字典的key 转换为value
                    dictKeyToValue(approveVO);
                    list.add(BeanUtil.beanToMap(approveVO, false, true));
                }
            }
            if (pageNum == 1) {
                if (excelWriter == null) {
                    excelWriter = excelCommonHelper.createExcelWriter(excelModelVO, destFilePath, Integer.parseInt(total));
                }
                excelCommonHelper.writeMap(excelWriter, list);
            } else {
                excelCommonHelper.writeMap(excelWriter, list);
            }
            if (pageInfo.isHasNextPage()) {
                pageNum = pageNum + 1;
                setData(excelModelVO, excelWriter, destFilePath, vo, pageNum);
            } else {
                closeFlag = true;
            }
        } catch (AppException appEx) {
            throw appEx;
        } catch (Exception e) {
            throw new AppException("调用自定义写入服务异常:" + e.getMessage());
        } finally {
            if (closeFlag && excelWriter != null) {
                excelWriter.close();
            }
        }
    }


    private void dictKeyToValue(EduSyncJhApproveVO approveVO) {
        //转换学段
        if (StringUtils.isNotBlank(approveVO.getSchoolCategory())) {
            DictQueryVO dictQueryVO = new DictQueryVO();
            dictQueryVO.setDictField("SCHOOLCATEGORY");
            dictQueryVO.setDictKey(approveVO.getSchoolCategory());
            String schoolCategory = dictIntegration.getValue(dictQueryVO);
            approveVO.setSchoolCategory(schoolCategory);
        }

        //转换证件类型
        if (StringUtils.isNotBlank(approveVO.getCardType())) {
            DictQueryVO dictQueryVO = new DictQueryVO();
            dictQueryVO.setDictField("CARDTYPE");
            dictQueryVO.setDictKey(approveVO.getCardType());
            String cardType = dictIntegration.getValue(dictQueryVO);
            approveVO.setCardType(cardType);
        }

        //校验审核状态
        if (StringUtils.isNotBlank(approveVO.getApproveState())) {
            DictQueryVO dictQueryVO = new DictQueryVO();
            dictQueryVO.setDictField("APPROVESTATE");
            dictQueryVO.setDictKey(approveVO.getApproveState());
            String approveState = dictIntegration.getValue(dictQueryVO);
            approveVO.setApproveState(approveState);
        }
    }
}
